package org.ephone;

import org.ephone.DeepContactsActivity.CallEndedListener;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentUris;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.provider.BaseColumns;
import android.provider.Contacts.People;
import android.provider.Contacts.PeopleColumns;
import android.provider.Contacts.PhonesColumns;
import android.telephony.PhoneStateListener;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class ContactsActivity extends Activity implements OnClickListener, DialogInterface.OnClickListener {
	
	// Calling the DeepContact Activity
	private Intent deepContactsAct;
	
	// Menu
	private AlertDialog.Builder dialogListMenu;
	AlertDialog dialogMenu;
	int menuItemSelected = 1;
	CharSequence[] menuItems;
	
	// Command listening and key generation
	KeyGenerator keyThread;
	public Handler handler;
	
	// Preferred Contacts
	public static final String PREFS_CONTACTS = "preferredContacts";
	private int [] preferredIds = {-1, -1, -1};
	private String [] preferredNums = {"", "", ""};
	SharedPreferences settings;
	
	// Calls
	private Intent callIntent;
	//private PhoneStateListener mListener;
	
	// Graphics buttons
	Button open_contacts;
	Button pref_buttons[] = new Button[3];
	
	// Query contacts members
	private String contactsFields[] = new String [] { BaseColumns._ID, PeopleColumns.NAME, PhonesColumns.NUMBER };
	private Cursor contacts_cursor;
	
	// DEBUG
	public Toast test;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.contacts_first);
        
        test = Toast.makeText(getApplicationContext(), "test Toast created", Toast.LENGTH_LONG);

        // MENU
        CharSequence[] tmp  = {getString(R.string.menu_back_option), 
    			getString(R.string.set_pref_contact1), 
    			getString(R.string.set_pref_contact2), 
    			getString(R.string.set_pref_contact3)};
        menuItems = tmp;
		dialogListMenu = new AlertDialog.Builder(this);
		dialogListMenu.setTitle("Choose an operation");
		dialogListMenu.setSingleChoiceItems(menuItems, 1, this);
		dialogMenu = dialogListMenu.create();
        
		// GRAPHICS
        open_contacts = (Button) findViewById(R.id.open_contacts_butt);
        pref_buttons[0] = (Button) findViewById(R.id.first_pref_contact);
        pref_buttons[1] = (Button) findViewById(R.id.second_pref_contact);
        pref_buttons[2] = (Button) findViewById(R.id.third_pref_contact);
        
        open_contacts.setOnClickListener(this);
        pref_buttons[0].setOnClickListener(this);
        pref_buttons[1].setOnClickListener(this);
        pref_buttons[2].setOnClickListener(this);
        open_contacts.requestFocus();
        
        // Preferences
        settings = getSharedPreferences(PREFS_CONTACTS, 0);
        preferredIds[0] = settings.getInt("id0", -1);
        preferredIds[1] = settings.getInt("id1", -1);
        preferredIds[2] = settings.getInt("id2", -1);
        onChangePrefs();
        
        // Key commands
        handler = new Handler(Looper.getMainLooper());
    }
	
	public void onChangePrefs(){
		
		// XXX To be verified
		for (int i = 0; i < 3; i++){
			int _id = settings.getInt("id"+(new Integer(i)).toString(), -1);
			
			// If the current id is null
			if (_id == -1){
				preferredIds[i] = _id;
				pref_buttons[i].setVisibility(View.INVISIBLE);
			} else { // If it is a good quantity
				int indexVisible = i;
				if (i == 0 || (i > 0 && preferredIds[i-1] != -1)){
					preferredIds[i] = _id;
					pref_buttons[i].setVisibility(View.VISIBLE);
				} else if (i > 0 && preferredIds[i-1] == -1){
					indexVisible = i - 1;
					preferredIds[i - 1] = _id;
					pref_buttons[i - 1].setVisibility(View.VISIBLE);
					preferredIds[i] = -1;
					pref_buttons[i].setVisibility(View.INVISIBLE);
				}
				
				contacts_cursor = getContentResolver().query(ContentUris.withAppendedId(People.CONTENT_URI, preferredIds[indexVisible]), contactsFields, null, null, null);
				
				if (contacts_cursor.moveToFirst()){
					int nameColumn = contacts_cursor.getColumnIndex(PeopleColumns.NAME);
		    		int phoneColumn = contacts_cursor.getColumnIndex(PhonesColumns.NUMBER);
		    		String _name = contacts_cursor.getString(nameColumn);
	    			String _phone = contacts_cursor.getString(phoneColumn);
	    			pref_buttons[indexVisible].setText(_name);
	    			preferredNums[indexVisible] = "tel:" + _phone;
				} else {
					pref_buttons[indexVisible].setVisibility(View.INVISIBLE);
				}
			}
		}
	}
	
	@Override
	public void onStart(){
		super.onStart();		
	}
	
	@Override
	public void onPause(){
		super.onPause();
		try {
			keyThread.exitActivity();
			keyThread = null;
			((ePhoneApp)getApplicationContext()).mListener = null;
		} catch (Exception ee) {
			test.setText(ee.toString());
			test.show();
		}
	}
	
	@Override
	public void onResume(){
		super.onResume();
		onChangePrefs();
		keyThread = new KeyGenerator(this, 0);
		keyThread.start();
		// CALLS
		((ePhoneApp)getApplicationContext()).mListener = (new DeepContactsActivity()).new CallEndedListener(this, 0);
        ((ePhoneApp)getApplicationContext()).mTelMgr.listen(((ePhoneApp)getApplicationContext()).mListener, PhoneStateListener.LISTEN_CALL_STATE);
	}
	
	@Override
	public boolean onKeyDown (int keyCode, KeyEvent event) {
		int countPrefs = 0;
		for (int i = 0; i < 3; i++)
			if (preferredIds[i] != -1)
				countPrefs++;
			
		switch(keyCode){
			case KeyEvent.KEYCODE_DPAD_DOWN:
			case KeyEvent.KEYCODE_DPAD_RIGHT:
				if (dialogMenu.isShowing()){
					if (menuItemSelected < menuItems.length-1)
						menuItemSelected++;
					else
						menuItemSelected = 0;
					
					dialogMenu.hide();
					dialogListMenu.setSingleChoiceItems(menuItems, menuItemSelected, this);
					dialogMenu = dialogListMenu.create();
					dialogMenu.show();

				} else {
					if (countPrefs == 0 || pref_buttons[2].isFocused())
						return true;
					else if (open_contacts.isFocused() && countPrefs > 0)
						pref_buttons[0].requestFocus();
					else if (pref_buttons[0].isFocused() && countPrefs > 1)
						pref_buttons[1].requestFocus();
					else if (countPrefs > 2)
						pref_buttons[2].requestFocus();
				}
				break;
			
			case KeyEvent.KEYCODE_DPAD_UP:
			case KeyEvent.KEYCODE_DPAD_LEFT:
				if (dialogMenu.isShowing()){
					if (menuItemSelected > 0)
						menuItemSelected--;
					else
						menuItemSelected = menuItems.length-1;
					
					dialogMenu.hide();
					dialogListMenu.setSingleChoiceItems(menuItems, menuItemSelected, this);
					dialogMenu = dialogListMenu.create();
					dialogMenu.show();
				} else {
					if (open_contacts.isFocused() && countPrefs > 0)
						pref_buttons[countPrefs-1].requestFocus();
					else if (pref_buttons[0].isFocused())
						open_contacts.requestFocus();
					else if (pref_buttons[1].isFocused())
						pref_buttons[0].requestFocus();
					else
						pref_buttons[1].requestFocus();
				}
			break;
			
			case KeyEvent.KEYCODE_DPAD_CENTER:
				if (dialogMenu.isShowing()) {
					this.onClick(dialogMenu, menuItemSelected);
				} else {
					if (open_contacts.isFocused() || countPrefs == 0){
						this.onClick(open_contacts);
					} else {
						this.onClick(this.getCurrentFocus());
					}
				}
				break;
		
			case KeyEvent.KEYCODE_MENU:
				dialogListMenu.setSingleChoiceItems(menuItems, menuItemSelected, this);
				dialogMenu = dialogListMenu.create();
				dialogMenu.show();
				break;
		}
		super.onKeyDown(keyCode, event);
		return true;
	}

	
	public void onClick(View v) {
		switch (v.getId()){
			case R.id.open_contacts_butt:
				deepContactsAct = new Intent(this, DeepContactsActivity.class);
				deepContactsAct.putExtra("preferredIndex", -1);
				startActivity(deepContactsAct);
				
				break;
			case R.id.first_pref_contact:
				try{
	                callIntent = new Intent(Intent.ACTION_CALL, Uri.parse(preferredNums[0]));
	                startActivity(callIntent);
				} catch (Exception ee){
					test.setText(ee.toString());
					test.show();
				}
				break;
			case R.id.second_pref_contact:
				try{
	                callIntent = new Intent(Intent.ACTION_CALL, Uri.parse(preferredNums[1]));
	                startActivity(callIntent);
				} catch (Exception ee){
					test.setText(ee.toString());
					test.show();
				}
				break;
			case R.id.third_pref_contact:
				try{
	                callIntent = new Intent(Intent.ACTION_CALL, Uri.parse(preferredNums[2]));
	                startActivity(callIntent);
				} catch (Exception ee){
					test.setText(ee.toString());
					test.show();
				}
				break;
			default:
				this.onClick(open_contacts);
		}
		
	}
	

	public void onClick(DialogInterface dialog, int which) {
		switch (which){
			case 0:
				super.onDestroy();
			    System.runFinalizersOnExit(true);
			    System.exit(0);
				break;
			case 1:
				deepContactsAct = new Intent(this, DeepContactsActivity.class);
				deepContactsAct.putExtra("preferredIndex", 0);
				startActivity(deepContactsAct);
				onChangePrefs();
				break;
			case 2:
				deepContactsAct = new Intent(this, DeepContactsActivity.class);
				deepContactsAct.putExtra("preferredIndex", 1);
				startActivity(deepContactsAct);
				onChangePrefs();
				break;
			case 3:
				deepContactsAct = new Intent(this, DeepContactsActivity.class);
				deepContactsAct.putExtra("preferredIndex", 2);
				startActivity(deepContactsAct);
				onChangePrefs();
				break;
		}
		this.onPause();
		dialogMenu.hide();
		dialogMenu = dialogListMenu.create();
	}
}
